<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="12" :offset="6">
        <el-form
          :model="form"
          :rules="rules"
          ref="testPaperForm"
          label-width="80px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="学科" prop="subId">
                <el-select
                  v-model="form.subId"
                  placeholder="请选择"
                  style="width: 100%"
                  @change="subjectChange"
                >
                  <el-option
                    v-for="item in subjectOptions"
                    :key="item.id"
                    :label="item.subject"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="参试班级" prop="classIdList">
                <el-select
                  v-model="form.classIdList"
                  placeholder="请选择"
                  style="width: 100%"
                  multiple
                >
                  <el-option
                    v-for="item in classList"
                    :key="item.id"
                    :label="item.className"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="试卷名称" prop="paperName">
                <el-input
                  v-model="form.paperName"
                  placeholder="请输入试卷名称"
                />
              </el-form-item>
              <el-form-item
                v-for="(item, index) in form.title"
                :label="'标题' + (index + 1)"
                :key="item.id"
              >
                <el-col :span="18">
                  <el-input v-model="item.value"></el-input
                ></el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="addQuestion(item)"
                    >添加题目</el-button
                  >
                  <el-button type="danger" @click="RemoveTitle(item)"
                    >删除</el-button
                  >
                </el-col>
                <template v-if="item.list.length > 0">
                  <el-card style="width: 100%">
                    <el-col
                      :span="24"
                      v-for="(it, ix) in item.list"
                      :key="it.id"
                    >
                      <el-row>
                        <el-col :span="2"> 题目{{ ix + 1 }}: </el-col>
                        <el-col :span="18">
                          <div v-html="it.content"></div>
                        </el-col>
                        <el-col :span="4">
                          <el-button
                            type="danger"
                            plain
                            icon="Delete"
                            @click="handleDeleteQuestion(item, it)"
                          ></el-button> </el-col
                      ></el-row>

                      <template v-if="it.topicId == 1 || it.topicId == 2">
                        <el-row
                          :gutter="16"
                          justify="space-between"
                          style="margin-top: 16px"
                        >
                          <el-col
                            :xl="6"
                            :lg="6"
                            :md="6"
                            :sm="24"
                            :xs="24"
                            v-for="ele in JSON.parse(it.items)"
                            :key="ele.pre"
                          >
                            <span style="margin-right: 10px"
                              >{{ ele.pre }}:</span
                            >
                            <span>{{ ele.content }}</span>
                          </el-col>
                        </el-row></template
                      >
                      <el-divider
                        v-if="ix !== item.list.length - 1"
                      ></el-divider>
                    </el-col>
                  </el-card>
                </template>
              </el-form-item>
              <el-form-item label="建议时长" prop="duration">
                <el-input-number v-model="form.duration"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
      <el-col :span="12" :offset="6" style="text-align: center">
        <el-button type="success" @click="submitForm">提交</el-button>
        <el-button type="primary" @click="addTitle">添加标题</el-button>
      </el-col>
    </el-row>
    <el-dialog title="请选择题目" v-model="open" width="1000px" append-to-body>
      <el-row :gutter="20">
        <el-col :span="24" :xs="24">
          <el-form :model="queryParams" ref="queryRef" inline>
            <el-form-item label="题干名称" prop="content">
              <el-input
                v-model="queryParams.content"
                placeholder="请输入题干名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="题目类型" prop="topicId">
              <el-select
                v-model="queryParams.topicId"
                placeholder="请选择"
                @change="handleQuery"
              >
                <el-option
                  v-for="item in topicTypeList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table
            :data="questionList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="编号" width="50" align="center" />
            <el-table-column
              label="题型"
              width="100"
              align="center"
              key="topicName"
              prop="topicName"
            />
            <el-table-column
              label="所属学科"
              align="center"
              key="subName"
              prop="subName"
              width="200"
              show-overflow-tooltip
            />

            <el-table-column
              label="题干名称"
              align="center"
              key="content"
              prop="content"
              show-overflow-tooltip
            >
              <template #default="scope">
                <span v-html="scope.row.content"></span>
              </template>
            </el-table-column>
            <el-table-column
              label="分数"
              align="center"
              key="score"
              prop="score"
              width="50"
            />
            <el-table-column
              label="难度"
              align="center"
              key="difficult"
              prop="difficult"
              width="150"
            >
              <template #default="scope">
                <el-rate disabled v-model="scope.row.difficult"></el-rate>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getQuestionList"
          />
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="selectQuestion">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CreateExamination">
import { getSchoolClassList } from "@/api/core/class";
import { getSubjectList } from "@/api/core/subject";
import { getQuestionList } from "@/api/core/question";
import {
  addTestPaper,
  editTestPaper,
  getTestPaperDetail,
} from "@/api/core/testPaper";
import {
  getCurrentInstance,
  reactive,
  ref,
  toRefs,
  watch,
  computed,
} from "vue";
import { parseTime } from "@/utils/ruoyi";
import useUserStore from "@/store/modules/user";
const topicTypeList = ref([
  { id: 1, label: "单选" },
  { id: 2, label: "多选" },
  { id: 3, label: "判断" },
  { id: 5, label: "填空" },
  { id: 6, label: "简答" },
  { id: 7, label: "编程题" },
]);
const { proxy } = getCurrentInstance();
const classList = ref([]);
const subjectOptions = ref([]);
const questionList = ref([]);
const selectQuesList = ref([]);
const total = ref(0);
const open = ref(false);
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const data = reactive({
  form: {
    id: null,
    title: [
      {
        value: "",
        id: 1,
        list: [],
      },
    ],
    subId: "",
    classIdList: [],
    paperName: "",
    duration: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    topicId: undefined,
    content: undefined,
  },
  currentRow: {},
  rules: {
    subId: [{ required: true, trigger: "blur", message: "学科不能为空" }],
    classIdList: [
      { required: true, trigger: "change", message: "参试班级不能为空" },
    ],
    paperName: [
      {
        required: true,
        trigger: ["blur"],
        message: "试卷名称能为空",
      },
    ],
    duration: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: "建议时长不能为空",
      },
    ],
  },
});
const { queryParams, form, rules, currentRow } = toRefs(data);

/** 查询班级列表 */
function getClassList() {
  getSchoolClassList().then((res) => {
    classList.value = res.rows;
  });
}
// 查询学科列表
function getSubList() {
  getSubjectList().then((res) => {
    subjectOptions.value = res.rows;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getQuestionTable();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 选择条数  */
function handleSelectionChange(selection) {
  selectQuesList.value = selection;
}
function handleStudentChange(selection) {
  studentSelect.value = selection.map((item) => item.userId);
}

/** 重置操作表单 */
function reset() {
  form.value = {
    id: null,
    className: "",
    classCode: "",
  };
  proxy.resetForm("testPaperForm");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

// 添加标题
function addTitle() {
  form.value.title.push({
    value: "",
    id: form.value.title.length + 1,
    list: [],
  });
}
// 删除标题
function RemoveTitle(item) {
  let index = form.value.title.indexOf(item);
  if (index !== -1) {
    form.value.title.splice(index, 1);
  }
}
/** 删除按钮操作 */
function handleDeleteQuestion(row, child) {
  let index = row.list.indexOf(child);
  if (index !== -1) {
    row.list.splice(index, 1);
  }
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["testPaperForm"].validate((valid) => {
    if (valid) {
      if (form.value.title.length > 0) {
        if (form.value.title.every((it) => it.list.length > 0)) {
          let param = {
            subId: form.value.subId,
            typeId: 1,
            classIdList: form.value.classIdList,
            paperName: form.value.paperName,
            duration: form.value.duration,
            titles: form.value.title.map((item) => {
              return {
                title: item.value,
                questionIdList: item.list.map((it) => it.id),
              };
            }),
          };
          if (form.value.id) {
            let obj = Object.assign(param, { id: form.value.id });
            editTestPaper(obj).then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              handleBack();
            });
          } else {
            addTestPaper(param).then((response) => {
              proxy.$modal.msgSuccess("新增成功");
              handleBack();
            });
          }
        } else {
          proxy.$modal.msgWarning("每个标题下至少一个题目");
        }
      } else {
        proxy.$modal.msgWarning("请至少添加一个标题");
      }
    }
  });
}
// 返回试卷列表
function handleBack() {
  const obj = { path: "/examination/create" };
  proxy.$tab.closeOpenPage(obj);
  router.push({ path: "/examination/examinationList" });
}
function getQuestionTable() {
  getQuestionList(
    Object.assign({ subjectId: form.value.subId }, queryParams.value)
  ).then((res) => {
    questionList.value = res.rows;
    total.value = res.total;
  });
}
// 添加题目
function addQuestion(row) {
  currentRow.value = row;
  if (form.value.subId) {
    open.value = true;
    getQuestionTable();
  } else {
    proxy.$modal.msgWarning("请选择学科");
  }
}
function subjectChange() {
  form.value.title = [
    {
      value: "",
      id: 1,
      list: [],
    },
  ];
  form.value.paperName = "";
}
/** 添加题目确认 */
function selectQuestion() {
  open.value = false;
  let findObj = form.value.title.find((item) => item.id == currentRow.value.id);
  console.log("dafafdaf", findObj);
  findObj.list = findObj.list.concat(selectQuesList.value);
  console.log(form.value);
}
// 监听路由变化
watch(
  () => route.query,
  (newValue, oldValue) => {
    if (newValue.paperId) {
      getTestPaperDetail(newValue.paperId).then((res) => {
        console.log("打印试卷详情", res);
        form.value.subId = res.data.subId;
        form.value.classIdList = res.data.classInfoList.map((item) => item.id);
        form.value.paperName = res.data.paperName;
        form.value.duration = res.data.duration;
        form.value.title = res.data.titles.map((item, index) => {
          return {
            value: item.title,
            id: index + 1,
            list: item.questionInfoList,
          };
        });
        form.value.id = res.data.id;
      });
    } else {
      form.value = {
        id: null,
        title: [
          {
            value: "",
            id: 1,
            list: [],
          },
        ],
        subId: "",
        classIdList: [],
        paperName: "",
        duration: "",
      };
    }
  },
  { immediate: true }
);
getClassList();
getSubList();
</script>

<style scoped lang="scss"></style>
